﻿namespace MvcCss
{
	using System.Collections.Generic;
	using System.Web;
	using System.Web.Mvc;
	using System.Web.Routing;

	public static class BodyExtensions
	{
		public static MvcBody BeginBody(this HtmlHelper htmlHelper)
		{
			return BeginBody(htmlHelper, new RouteValueDictionary());
		}

		public static MvcBody BeginBody(this HtmlHelper htmlHelper, object htmlAttributes)
		{
			return BeginBody(htmlHelper, new RouteValueDictionary(htmlAttributes));
		}		

		public static MvcBody BeginBody(this HtmlHelper htmlHelper, IDictionary<string, object> htmlAttributes)
		{
			return BodyHelper(htmlHelper, htmlAttributes);
		}
		
		public static void EndBody(this HtmlHelper htmlHelper)
		{
			HttpResponseBase httpResponse = htmlHelper.ViewContext.HttpContext.Response;
			httpResponse.Write("</body>");
		}

		private static MvcBody BodyHelper(this HtmlHelper htmlHelper, IDictionary<string, object> htmlAttributes)
		{
			TagBuilder tagBuilder = new TagBuilder("body");
			tagBuilder.MergeAttributes(htmlAttributes);
			string controller = htmlHelper.ViewContext.RouteData.Values["controller"].ToString().ToLower();
			tagBuilder.AddCssClass(controller);
			string action = htmlHelper.ViewContext.RouteData.Values["action"].ToString().ToLower();
			tagBuilder.MergeAttribute("id", controller + "-" + action);

			HttpResponseBase httpResponse = htmlHelper.ViewContext.HttpContext.Response;
			httpResponse.Write(tagBuilder.ToString(TagRenderMode.StartTag));
			return new MvcBody(htmlHelper.ViewContext.HttpContext.Response);
		}
	}
}
